package com.example.eback.service;
import com.example.eback.result.ProcessResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.example.eback.dao.OrganInfoDAO;
import com.example.eback.entity.OrganInfo;
import org.springframework.web.client.RestTemplate;

@Service
public class OrganInfoService {
    @Autowired
    private OrganInfoDAO organInfoDAO;
    public ProcessResponse MeasurementOrganInfo(String originFileUrl,String predictFileUrl){
        RestTemplate restTemplate = new RestTemplate();
        String flaskUrl = "http://10.134.48.122:5000/measurement";

        // Create a map to store the parameters
        Map<String, String> params = new HashMap<>();
        params.put("originFileUrl", originFileUrl);
        params.put("predictFileUrl", predictFileUrl);

        // Set the headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, String>> entity = new HttpEntity<>(params, headers);

        // Send the request to the flask server
        ResponseEntity<Map> response = restTemplate.exchange(flaskUrl, HttpMethod.POST, entity, Map.class);

        // Extract the returned data
        Map<String, Map<String, Double>> measurements = (Map<String, Map<String, Double>>) response.getBody().get("measurements");

        // Save the data to the database
        saveMeasurements(originFileUrl, measurements);
        ProcessResponse processResponse = new ProcessResponse();
        processResponse.setOriginFileUrl(originFileUrl);
        processResponse.setPredictFileUrl(predictFileUrl);
        return processResponse;
    }

    public void saveMeasurements(String fileUrl, Map<String, Map<String, Double>> measurements) {

        for (Map.Entry<String, Map<String, Double>> entry : measurements.entrySet()) {
            String organName = entry.getKey();
            Map<String, Double> values = entry.getValue();
            OrganInfo organInfo = new OrganInfo();
            organInfo.setFileUrl(fileUrl);
            organInfo.setOrganName(organName);
            organInfo.setDiameterX(values.get("Diameter in X"));
            organInfo.setDiameterY(values.get("Diameter in Y"));
            organInfo.setDiameterZ(values.get("Diameter in Z"));
            organInfo.setVolume(values.get("Volume"));
            organInfo.setArea(values.get("Area"));
            organInfo.setFlatness(values.get("Flatness"));
            organInfo.setElongation(values.get("Elongation"));
            organInfoDAO.save(organInfo);
        }
    }
}
